import { getToken, setToken } from '@/utils';

const INITIAL_STATE = {
  token: getToken(),
  userInfo: JSON.parse(sessionStorage.getItem('userInfo') || 'null') || {
    userAccount: null,
  },
};

const LOGOUT = Symbol('user.logout');
const LOGIN = Symbol('user.login');
const SET_TOKEN = Symbol('user.setToken');

const user = (state = INITIAL_STATE, { type, ...action }) => {
  switch (type) {
    case LOGOUT:
      setToken();
      sessionStorage.removeItem('userInfo');
      if (window.top !== window) {
        setTimeout(() => {
          window.top.sessionStorage.clear();
          window.top.localStorage.clear();
          window.top.location.hash = '#/login';
        }, 3e3);
      } else {
        window.location.hash = '#/login';
      }

      return {
        token: '',
        userInfo: {},
      };

    case SET_TOKEN:
      setToken(action.token);
      return {
        ...state,
        token: action.token,
      };

    case LOGIN:
      setToken(action.token);
      sessionStorage.setItem('userInfo', JSON.stringify(action.userInfo));
      return {
        token: action.token,
        userInfo: action.userInfo,
      };

    default:
      return state;
  }
};

export const isDispatchLogout = () => !!sessionStorage.getItem('Admin.isDispatchLogout');

export const UserActions = {
  logout() {
    sessionStorage.setItem('Admin.isDispatchLogout', '1');
    setTimeout(() => {
      sessionStorage.removeItem('Admin.isDispatchLogout');
    });
    return (dispatch) => {
      dispatch({ type: LOGOUT });
      dispatch({ type: 'APP_RESET' });
    };
  },
  login(token, userInfo) {
    return { type: LOGIN, token, userInfo };
  },
  setToken(token) {
    return { type: SET_TOKEN, token };
  },
};
export default user;
